/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.sdgakj.web.account;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.sdgakj.entity.User;
import com.sdgakj.enums.EnumUserType;
import com.sdgakj.service.account.AccountService;
import com.sdgakj.service.account.ShiroDbRealm.ShiroUser;
import com.sdgakj.service.login.UserLoginService;
import com.sdgakj.service.user.UserService;
import com.sdgakj.utils.DateUtil;
import com.sdgakj.utils.LoginAdminUtil;
import com.sdgakj.utils.RedisClient;

/**
 * 找回密码的Controller.
 * 
 * @author calvin
 */
@Controller
@RequestMapping(value = "/retrieve")
public class RetrieveController {

	@Autowired
	private AccountService accountService;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private UserLoginService userLoginService;
	
	private static Logger logger = LoggerFactory.getLogger(RetrieveController.class);

	
	@RequestMapping(method = RequestMethod.POST)
	public String register(String mobile, String code, String plainPassword, RedirectAttributes redirectAttributes) {
		
		User user = userService.getAdminByTell(mobile, EnumUserType.ADMIN.getCode());
		if(user == null) {
			redirectAttributes.addFlashAttribute("message", "手机号不存在！");
			redirectAttributes.addFlashAttribute("tag","1");//页面状态记号
			return "redirect:/login";
		}
		
		int times = getLoginValidateTimes(mobile);
		if(times > 5) {
			redirectAttributes.addFlashAttribute("message", "验证码失败超过5次，今日无法找回密码！");
			redirectAttributes.addFlashAttribute("tag","1");//页面状态记号
			return "redirect:/login";
		}
		
		String c = RedisClient.cacheGet(mobile + "_code");
		if (c != null && c.equals(code)) {
			user.setPlainPassword(plainPassword);
			accountService.updateUser(user);
			redirectAttributes.addFlashAttribute("message", "更改密码成功！");
			return "redirect:/login";
		}else {
			// 当天超过5次后手机号不能修改密码
			redirectAttributes.addFlashAttribute("message", "验证码错误！");
			redirectAttributes.addFlashAttribute("tag","1");//页面状态记号
			return "redirect:/login";
		}
		
	}
	
	public int getLoginValidateTimes(String mobile) {
		String times = RedisClient.cacheGet("lvt_" + mobile + "_times_" + DateUtil.formatDateToString(new Date(), "yyyyMMdd"));
		times = times == null?"+":times + "+";
		RedisClient.cacheAdd("lvt_" + mobile + "_times_" + DateUtil.formatDateToString(new Date(), "yyyyMMdd"),times, 60 * 60 * 24);
		return times.length();
	}
	
	/**
	 * Ajax请求发送code。
	 */
	@RequestMapping(value = "sendCode")
	@ResponseBody
	public String checkLoginName(String mobile) {
//		User user = userService.getAdminByTell(mobile, EnumUserType.ADMIN.getCode());;
		List<User> userList=userService.getAdminByMobile(mobile, EnumUserType.ADMIN.getCode());
		User user =null;
		if(CollectionUtils.isNotEmpty(userList)){
			user=userList.get(0);
		}
		if(user != null) {
			try {
				logger.info("admin find password start:" + mobile);
//				String result =	SMSSender.sendValidateCode(mobile);
				userLoginService.sendSmsCode(mobile);
				return "0";
			} catch (Exception e) {
				logger.error("admin find password error:" + e.getMessage());
				return "-1";
			}
		}else {
			return "1";
		}
		
	}
	
	public static void main(String[] args) {
		System.out.println(new RetrieveController().getLoginValidateTimes("1234567"));
	}
	
	/**
	 * 登录提交
	 * @param entity		登录的UUser
	 * @param rememberMe	是否记住
	 * @param request		request，用来取登录之前Url地址，用来登录后跳转到没有登录之前的页面。
	 * @return
	 */
	@RequestMapping(value="submitLogin",method=RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> submitLogin(User entity,Boolean rememberMe,HttpServletRequest request){
		 Map<String, Object> resultMap = new LinkedHashMap<String, Object>();
		try {
			ShiroUser shiroUser = LoginAdminUtil.login(entity,rememberMe);
			resultMap.put("status", 200);
			resultMap.put("message", "登录成功");
			
			//获取用户未登录之前的地址
			String url = (String) request.getAttribute(WebUtils.FORWARD_REQUEST_URI_ATTRIBUTE);
			//如果登录之前没有地址，那么就跳转到首页。
			if(StringUtils.isBlank(url)){
				url = "/welcome";
			}
			//跳转地址
			resultMap.put("back_url", url);
		/**
		 * 这里其实可以直接catch Exception，然后抛出 message即可，但是最好还是各种明细catch 好点。。
		 */
		} catch (DisabledAccountException e) {
			resultMap.put("status", 500);
			resultMap.put("message", "帐号已经禁用。");
		} catch (Exception e) {
			resultMap.put("status", 500);
			resultMap.put("message", "帐号或密码错误");
		}
			
		return resultMap;
	}
	
}
